#!/bin/csh

if( $#argv < 2 ) then
    echo "USAGE:"
    echo "------"
    echo "WarpScr <target_name> <object_name> [log=log_file] [level=level] "
    echo ""
    echo "Description:"
    echo "------------"
    echo "Runs cubic spline registration pipeline using specified target and object."
    echo "Uses match criterion, isotropic sample size, and multi-grid hierarchy"
    echo " as described below"
    echo "Uses running estimates of bias field inhomogeneity ratios to correct"
    echo " object volume for better warping" 
    echo ""
    echo "Warps object ONTO target (i.e. arg 2 ONTO arg 1), therefore inverse"
    echo "  transformation of target will look like object."
    echo ""
    echo "Does the following steps:"
    echo "-------------------------"
    echo "Preprocessing steps: "
    echo "    Undersample target and object volumes to 1.2 mm isotropic voxel size"
    echo "    Smooth images using 2.4 and 4.8 mm FWHM  Gaussian kernels"
    echo ""
    echo "Registration:"
    echo "    Use cubic spline multigrid registration with hierarchy of grid sizes"
    echo ""
    echo "Uses the following parameters:"
    echo "------------------------------"
    echo "Input:"
    echo "*target name: image that the other is warped to"
    echo "*object name: image that is warped ONTO target"
    echo ""
    echo "Optional input:"
    echo "---------------"
    echo "level=N"
    echo "specify the warping hierarchy only down to level N (e.g. 1, 2 etc), 3 by default"
    echo ""
    echo "log=log_file"
    echo "specify the log file"
    echo ""
    echo "Hard coded:"
    echo "*Match criterion: CC (cross correlation)"
    echo "*Undersample image voxel size: 1.2 mm"
    echo "*Multi-grid hierarchy: 24 12 6 4.8 2.4"
    echo "--These are all integral multiples of the isotropic size"
    exit
endif

# bin directory
set bindir = ~/FXTAS/bin/

# match criterion
set CC = "CC"

# voxel undersample size
set size = 1.2

set transform = ~/FXTAS/bin/transformL3

set coreg = ~/FXTAS/bin/spline_coregQS20

# process the parameters
set level = 2
set coreglog = coreglog

set name3 = `echo $3 | awk '{split($0,a,"="); print a[1]}'`
set value3 = `echo $3 | awk '{split($0,a,"="); print a[2]}'`
set name4 = `echo $4 | awk '{split($0,a,"="); print a[1]}'`
set value4 = `echo $4 | awk '{split($0,a,"="); print a[2]}'`
if ( $name3 == "level" ) then
  set level = $value3
else if ( $name3 == "log" ) then 
  set coreglog = $value3
endif
if ( $name4 == "level" ) then
  set level = $value4
else if ( $name4 == "log" ) then 
  set coreglog = $value4
endif

set levelcount = 1

set one = 24
set two = 12
set three = 6
set four = 4.8
set five = 2.4

if ( ! -e $coreglog ) then
  touch $coreglog
endif

echo "============================================================" >> $coreglog
echo "`date`" >> $coreglog
echo "RUN BY `uname -n`" >> $coreglog
echo "for this run: to level ${level}" >> $coreglog
echo "============================================================" >> $coreglog

# set the basic names of target and object

# internal conversions to analyze format
set ptbase = ${1:r}
set pobase = ${2:r}

set ptarget = ${ptbase}.hdr
set target = ${ptarget:r}_normMeanF.hdr

set pobject = ${pobase}.hdr
set object = ${pobject:r}_normMeanF.hdr

set s_obj = ${pobject:r}_s
set s_targ = ${ptarget:r}_s
set ss_obj = ${pobject:r}_ss
set ss_targ = ${ptarget:r}_ss

# Testing if we need preprocessing
if ( ! -e ${ss_obj}.hdr || ! -e ${ss_targ}.hdr ) then
  # do the preprocessing steps
  set targname="iso_${target:r:t}"
  set objname = "iso_${object:r:t}"

  # normalize the means of target and object to 150: write float versions
  echo "====== No warping was previously done, preprocessing ..." >> $coreglog
  echo "creating ${target} and ${object} ..." >> $coreglog
  ${bindir}chg_data ${ptarget} -normalizeFloatMean 150
  ${bindir}chg_data ${pobject} -normalizeFloatMean 150

  # create the required object files: targets are already made
  echo "creating $ss_obj ..." >> $coreglog
  $transform "${object:r}.hdr" -voxmms $size $size $size -outname $objname
  #ln -s "${objname}.hdr" obj.hdr
  #ln -s "${objname}.img" obj.img
  ${bindir}chg_data "${objname}.hdr" -smooth ${five} ${five} ${five} -outname $s_obj 
  ${bindir}chg_data ${s_obj}.hdr -smooth ${four} ${four} ${four} -outname $ss_obj 

  # create the required object files: targets are already made
  echo "creating $ss_targ ..." >> $coreglog
  $transform "${target:r}.hdr" -voxmms $size $size $size -outname $targname
  #ln -s "${targname}.hdr" targ.hdr
  #ln -s "${targname}.img" targ.img
  ${bindir}chg_data "${targname}.hdr" -smooth ${five} ${five} ${five} -outname $s_targ
  ${bindir}chg_data ${s_targ}.hdr -smooth ${four} ${four} ${four} -outname $ss_targ

  rm ${objname}*
  rm ${targname}*
endif   

# Testing if level 1 has been done. If not, do it.
if ( ! -e params.${one} ) then
  # WARP LEVEL 1, match the double smoothed images
  echo "====== WARP LEVEL 1, match the double smoothed images" >> $coreglog
  date >> $coreglog
  echo "$coreg ${ss_targ}.hdr ${ss_obj}.hdr ${CC} -g ${one} " >> $coreglog
  $coreg ${ss_targ}.hdr ${ss_obj}.hdr ${CC} -g ${one}
  # see if Out.params is really generated
  if ( -e Out.params  ) then 
    mv Out.params params.${one}
    mv C3SpTransformLog Log.${one}
    mkdir $one
    mv Q* $one
    mv P* $one
    mv Penalty* ${one}
    mv Padded* ${one}
    mv *PadR* ${one}
    cp params.$one ${one}
    #mv BiasRatioEst* ${one}
    #mv *Adjusted* ${one}
    rm BiasRatioEst*
    #mv *TP* ${one}
    rm *TP* 
    mv Unsmoothed* ${one}
    mv Grid* ${one}
  else
    echo "======= WARP LEVEL 1 failed" >> $coreglog
    echo "Let's clean up everthing and do it again." >> $coreglog 
    date >> $coreglog
    rm -rf *
    exit 1
  endif
else
  echo "======= WARP LEVEL 1 was previously done " >> $coreglog
  date >> $coreglog
endif

@ levelcount ++
if ( ${levelcount} > ${level} ) then
  cp params.${one} final_params
  echo "completed run to level ${level}: ${one}" >> $coreglog
  echo "completion time: `date`" >> $coreglog
  echo "Warping is complete!  Goodbye!"
  exit
endif

# Testing if level 2 has been done. If not, do it. 
if ( ! -e params.${two} ) then
  # WARP LEVEL 2, first single-smooth match
  echo "====== WARP LEVEL 2, first single-smooth match" >> $coreglog
  date >> $coreglog
  echo "$coreg ${s_targ}.hdr ${s_obj}.hdr ${CC} -g ${two} -p params.$one" >> $coreglog
  $coreg ${s_targ}.hdr ${s_obj}.hdr ${CC} -g ${two} -p params.$one
  # see if Out.params is really generated
  if ( -e Out.params  ) then 
    mv Out.params params.${two}
    mv C3SpTransformLog Log.${two}
    mkdir ${two}
    mv Q* ${two}
    mv P* ${two}
    mv Penalty* ${two}
    mv Padded* ${two}
    mv *PadR* ${two}
    cp params.${two} ${two}
    #mv BiasRatioEst* ${two}
    rm BiasRatioEst* 
    mv *Adjusted* ${two}
    #mv Log* ${two}
    #mv *TP* ${two}
    rm *TP* 
    mv Unsmoothed* ${two}
    mv Grid* ${two}
  else
    echo "======= WARP LEVEL 2 failed" >> $coreglog
    echo "Let's clean up the result from level 1 and do it again." >> $coreglog 
    date >> $coreglog
    rm -rf $one
    rm -f params.$one 
    exit 1
  endif
else
  echo "======= WARP LEVEL 2 was previously done " >> $coreglog
  date >> $coreglog
endif

@ levelcount ++
if ( ${levelcount} > ${level} ) then
  cp params.${two} final_params
  echo "completed run to level ${level}: ${two}" >> $coreglog
  echo "completion time: `date`" >> $coreglog
  echo "Warping is complete!  Goodbye!"
  exit
endif

# Testing if level 3 has been done. If not, do it. 
if ( ! -e params.${three} ) then
  # WARP LEVEL 3, second single-smooth match
  echo "====== WARP LEVEL 3, second single-smooth match" >> $coreglog
  date >> $coreglog
  echo "$coreg ${s_targ}.hdr ${s_obj}.hdr ${CC} -g ${three} -p params.${two}" >> $coreglog
  $coreg ${s_targ}.hdr ${s_obj}.hdr ${CC} -g ${three} -p params.${two} 
  # see if Out.params is really generated
  if ( -e Out.params  ) then 
    mv Out.params params.${three}
    mv C3SpTransformLog Log.${three}
    mkdir ${three}
    mv Q* ${three}
    mv P* ${three}
    mv Penalty* ${three}
    mv Padded* ${three}
    mv *PadR* ${three}
    cp params.${three} ${three}
    #mv BiasRatioEst* ${three}
    rm BiasRatioEst* 
    mv *Adjusted* ${three}
    #mv Log* ${three}
    #mv *TP* ${three}
    rm *TP* 
    mv Unsmoothed* ${three}
    mv Grid* ${three}
  else
    echo "======= WARP LEVEL 3 failed" >> $coreglog
    echo "Let's clean up the result from level 2 and do it again." >> $coreglog 
    date >> $coreglog
    rm -rf $two
    rm -f params.$two 
    exit 1
  endif
else
  echo "======= WARP LEVEL 3 was previously done " >> $coreglog
  date >> $coreglog
endif

@ levelcount ++
if ( ${levelcount} > ${level} ) then
  cp params.${three} final_params
  echo "completed run to level ${level}: ${three}" >> $coreglog
  echo "completion time: `date`" >> $coreglog
  echo "Warping is complete!  Goodbye!"
  exit
endif

# Testing if level 4 has been done. If not, do it. 
if ( ! -e params.${four} ) then
  # WARP LEVEL 4, match the non-smoothed but isotropic images
  echo "====== WARP LEVEL 4, match the non-smoothed but isotropic images" >> $coreglog
  date >> $coreglog
  echo "$coreg targ.hdr obj.hdr ${CC} -g ${four} -p params.${three}" >> $coreglog
  $coreg targ.hdr obj.hdr ${CC} -g ${four} -p params.${three}
  # see if Out.params is really generated
  if ( -e Out.params  ) then 
    mv Out.params params.${four}
    mv C3SpTransformLog Log.${four}
    mkdir ${four}
    mv Q* ${four}
    mv P* ${four}
    mv Penalty* ${four}
    mv Padded* ${four}
    mv *PadR* ${four}
    cp params.${four} ${four}
    #mv BiasRatioEst* ${four}
    rm BiasRatioEst* 
    mv *Adjusted* ${four}
    #mv Log* ${four}
    #mv *TP* ${four}
    rm *TP* 
    mv Unsmoothed* ${four}
    mv Grid* ${four}
  else
    echo "======= WARP LEVEL 4 failed" >> $coreglog
    echo "Let's clean up the result from level 3 and do it again." >> $coreglog 
    date >> $coreglog
    rm -rf $three 
    rm -f params.$three 
    exit 1
  endif
else
  echo "======= WARP LEVEL 4 was previously done " >> $coreglog
  date >> $coreglog
endif

@ levelcount ++
if ( ${levelcount} > ${level} ) then
  cp params.${four} final_params
  echo "completed run to level ${level}: ${four}" >> $coreglog
  echo "completion time: `date`" >> $coreglog
  echo "Warping is complete!  Goodbye!"
  exit
endif

# Testing if level 5 has been done. If not, do it. 
if ( ! -e params.${five} ) then
  # WARP LEVEL 5, match the non-smoothed but isotropic images
  echo "====== WARP LEVEL 5, final matching" >> $coreglog
  date >> $coreglog
  echo "$coreg targ.hdr obj.hdr ${CC} -g ${five} -p params.${four}" >> $coreglog
  $coreg targ.hdr obj.hdr ${CC} -g ${five} -p params.${four} 
  # see if Out.params is really generated
  if ( -e Out.params  ) then 
    mv Out.params params.${five}
    mv C3SpTransformLog Log.${five}
    mkdir ${five}
    mv Q* ${five}
    mv P* ${five}
    mv Penalty* ${five}
    mv Padded* ${five}
    mv *PadR* ${five}
    cp params.${five} ${five}
    #mv BiasRatioEst* ${five}
    rm BiasRatioEst* 
    mv *Adjusted* ${five}
    #mv Log* ${five}
    #mv *TP* ${five}
    rm *TP* 
    mv Unsmoothed* ${five}
    mv Grid* ${five}
  else
    echo "======= WARP LEVEL 5 failed" >> $coreglog
    echo "Let's clean up the result from level 4 and do it again." >> $coreglog 
    date >> $coreglog
    rm -rf $four 
    rm -f params.$four 
    exit 1
  endif
else
  echo "======= WARP LEVEL 5 was previously done " >> $coreglog
  date >> $coreglog
endif

cp params.${five} final_params
echo "completed run to level ${level}: ${five}" >> $coreglog
echo "completion time: `date`" >> $coreglog
echo "Warping is complete!  Goodbye!"
exit

